package com.ctgu.chatapp.view.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.RecyclerView
import com.ctgu.chatapp.Service.RequestService
import com.ctgu.chatapp.databinding.ItemFriendrequestBinding
import com.ctgu.chatapp.model.Database.DataBaseManager
import com.ctgu.chatapp.showPojo.FriendQuest
import com.ctgu.chatapp.utils.Utils
import com.ctgu.chatapp.view.DialogFragment.Response
import com.ctgu.chatapp.view.IMSApplication
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class RequestAdapter(var data: List<FriendQuest>, private val fragmentManager: FragmentManager) :
    RecyclerView.Adapter<RequestAdapter.ViewHolder>() {

    class ViewHolder(val binding: ItemFriendrequestBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = run {
        val binding =
            ItemFriendrequestBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        ViewHolder(binding)
    }

    override fun getItemCount() = data.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding.friend = data[position]
        holder.binding.accept.setOnClickListener {
            val response = Response(Utils.chatID, data[position].touId)
            response.showNow(fragmentManager, "好友设置")
        }
        holder.binding.refuse.setOnClickListener {
            CoroutineScope(Dispatchers.IO).launch {
                RequestService.sendFriendResponse(Utils.chatID, data[position].touId, 2, "")
                async {
                    DataBaseManager.getInstance(IMSApplication.context).getRequestDao()
                        .updateFriendRequest(2, Utils.chatID, data[position].touId)
                }
            }
        }
    }
}